package com.ken.callblock2;

import java.io.InputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import ken.app.helper.Helper;

import com.ken.callblock2.tools.KENLog;
import com.ken.callblock2.utils.ContactBean;
import com.ken.callblock2.utils.RecentCallBean;

import android.app.Application;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;

public class CallBlock2 extends Application {
	private static String TAG 						= CallBlock2.class.getSimpleName();
	private HashMap<String, String> blockNumbersMap = new HashMap<String, String>();
	private SharedPreferences preferences;
	
	public List<ContactBean> contactBeanList 		= new LinkedList<ContactBean>();
	public List<RecentCallBean> recentCallBeanList 	= new LinkedList<RecentCallBean>();
	public Handler blockListNotifyHandler;
	
	public CallBlock2() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		preferences = PreferenceManager.getDefaultSharedPreferences(this);
		getBlockNubMap();
	}

	@Override
	public void onLowMemory() {
		// TODO Auto-generated method stub
		super.onLowMemory();
	}
	
	private String getBlackNmb(){
		return preferences.getString("BLACK_LIST", "null");
	}
	
	
	private void setBlackNmb(){
		
		String data = "";
		if (blockNumbersMap.size() > 0) {
			Iterator iterator = blockNumbersMap.entrySet().iterator();
			while (iterator.hasNext()) {
				Map.Entry entry = (Entry) iterator.next();
				String number = (String) entry.getKey();
				String status = (String) entry.getValue();
				data = data + ":;:" + number + getString(R.string.number_split) + status;
			}
		}
		if (data.equals("")) {
			preferences.edit().putString("BLACK_LIST", "null").commit();
		}else{
			preferences.edit().putString("BLACK_LIST", data).commit();
		}
	}
	
	
	public Map<String, String> getBlockNubMap(){
		String data = getBlackNmb();
		blockNumbersMap.clear();
		
		if (!data.equals("null")) {
			String[] names = Helper.split(data, ":;:");
			for (String name : names) {
				String[] numbers = Helper.split(name, getString(R.string.number_split));
				blockNumbersMap.put(numbers[0], numbers[1]);
			}
		}
		return blockNumbersMap;
	}
	
	public void removeBlackItem(String blackNumber){
		blockNumbersMap.remove(blackNumber);
		setBlackNmb();
	}
	
	public void addBlackMap(String number, String status){
		if (number != null && !number.equals("") && status != null && !status.equals("")) {
			blockNumbersMap.put(number.replace(" ", ""), status);
			setBlackNmb();
		}
	}
	
    public List<String> removeDuplicate(List<String> list){
        HashSet<String> hashSet = new HashSet<String>(list); 
        list.clear(); 
        list.addAll(hashSet); 
        return list; 
    }
    
	public List<ContactBean> getContactToList() {
		List<ContactBean> contacts = contactBeanList;
		contacts.clear();
		// 陣列內容: 從contact撈出有顯示名稱的資料
		String[] temp = { 	ContactsContract.Contacts._ID,
							ContactsContract.Contacts.DISPLAY_NAME,
							ContactsContract.Contacts.PHOTO_ID,
							ContactsContract.Contacts.HAS_PHONE_NUMBER,
							ContactsContract.Contacts.LOOKUP_KEY,
							ContactsContract.CommonDataKinds.Phone.PHOTO_URI };
		Cursor cursor_Contact = getContentResolver().query(Contacts.CONTENT_URI, temp, null, null, null);
		cursor_Contact.moveToFirst();
		do {
			String contactId 	= cursor_Contact.getString(0); // 回傳有DISPLAY_NAME的資料,個人Device有59筆
			String lookup_key 	= cursor_Contact.getString(4);
			String contactName 	= cursor_Contact.getString(1);
			// String photo_id 	= cursor_Contact.getString(2);
			String lookupKey 	= cursor_Contact.getString(4);
			// byte[] photo 	= openPhoto(Long.valueOf(contactId));
			KENLog.e("ken", "******************");
			KENLog.e("ken", "lookup_key " + lookup_key);
			KENLog.e("ken", "contactName " + contactName);
			int numberCount 	= cursor_Contact.getInt(3);

			String image_uri 	= cursor_Contact.getString(5);

			// if (numberCount > 0) {
			// 取出所有電話
			// Cursor pCur =
			// getApp().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
			// null,
			// ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
			// new String[]{contactId},
			// null);
			// while (pCur.moveToNext()) {
			// String number =
			// pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).replaceAll(" ",
			// "");
			// ContactBean bean = new ContactBean();
			// bean.id = new String(contactId);
			// bean.name = new String(contactName);
			// bean.phone_number = new String(number);
			// bean.photo_id = photo_id;
			// if (photo != null) {
			// bean.photo = photo;
			// }
			// contacts.add(bean);
			// }
			// pCur.close();

			// Phone info are stored in the ContactsContract.Data table
			Uri phoneUri 			= ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
			String[] proj2 			= { ContactsContract.CommonDataKinds.Phone.NUMBER,
										ContactsContract.CommonDataKinds.Phone.PHOTO_ID };
			// using lookUp key to search the phone numbers
			String selection 		= ContactsContract.Data.LOOKUP_KEY + "=?";
			String[] selectionArgs 	= { lookupKey };
			Cursor cur 				= getContentResolver().query(phoneUri, proj2, selection, selectionArgs, null);
			while (cur.moveToNext()) {
				ContactBean bean 	= new ContactBean();
				bean.id 			= new String(contactId);
				bean.name 			= new String(contactName);
				bean.phone_number 	= new String(cur.getString(0));
				bean.photo_id 		= cur.getString(1);
				// if (bean.photo_id != null) {
				// bean.photo = openPhoto(Long.valueOf(bean.photo_id));
				// }
				if (image_uri != null) {
					InputStream iStream;
					try {
						iStream 	= getContentResolver().openInputStream(Uri.parse(image_uri));
						bean.photo 	= Helper.getBytes(iStream);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
				contacts.add(bean);
			}

			// }

		} while (cursor_Contact.moveToNext());

		cursor_Contact.close();
		return contacts;
	}
    
}
